﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.SalesOrder;
using ProTrack.IServices.StoreHouse;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Printing;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 销售订单接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderSaleController : ControllerBase
    {
        public OrderSaleController(IOrderSaleServices services,LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;

        }
        public IOrderSaleServices Services { get; }
        public LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有销售订单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetllAsync();
                status.Data = list;
                status.Count = list.Count();

            }
            catch (Exception ex)
            {

                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("销售订单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }
            
        /// <summary>
        /// 分页获取销售订单
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Number"></param>
        /// <param name="CustomerNumber"></param>
        /// <param name="WarehouseId"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get ([FromQuery] int PageIndex, [FromQuery] int PageSize,[FromQuery] string Number,[FromQuery] string CustomerNumber,[FromQuery] string WarehouseId,[FromQuery] string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                CustomerNumber = CustomerNumber ?? "";
                WarehouseId = WarehouseId ?? "";
                Status = Status ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, Number, CustomerNumber, WarehouseId, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, CustomerNumber, WarehouseId, Status);

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("销售订单-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据销售订单Id获取商品数据
        /// </summary>
        /// <param name="OrderSaleId"></param>
        /// <returns></returns>
        [HttpGet("GetOrderSaleId")]
        public async Task <IActionResult> GetOrderSaleId([FromQuery] string OrderSaleId,int WarehouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {   
                var list = await Services.GetOrderSalebyIdAsync(OrderSaleId,WarehouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("销售订单-获取商品数据", ex, HttpContext);
            }
            return Ok(status);
        }
            /// <summary>
            /// 新增销售订单
            /// </summary>
            /// <param name="model"></param>
            /// <param name="OrderSaleItemString"></param>
            /// <returns></returns>

        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderSale model, [FromForm] string OrderSaleItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderSaleItem> list = new List<OrderSaleItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderSaleItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderSaleItem>>(OrderSaleItemString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-新增", ex, HttpContext);
            }

            return Ok(status);
        }
        /// <summary>
        /// 修改销售订单
        /// </summary>
        /// <param name="model"></param>
        /// <param name="OrderSaleItemString"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderSale model, [FromForm] string OrderSaleItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderSaleItem> list = new List<OrderSaleItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderSaleItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderSaleItem>>(OrderSaleItemString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.OrderSaleId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSucces = await Services.UpdateAsync(model, list);
                if (isSucces)
                {
                    status.Msg = "修改成功";

                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-修改", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 批量删除销售订单
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 修改销售订单
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPut("UpdateOrderStatus")]
        public async Task <IActionResult> UpdateOrderStatus([FromForm] int Id, [FromForm]string Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var quoto = await Services.UpdateOrderStatus(Id, Status);

                if (quoto == null)
                {
                    status.Code = -1;
                    status.Msg = "未找到该报价单";
                }
                else
                {
                    status.Code = 0;
                    status.Msg = "报价单状态更新成功";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("报价单-修改", ex, HttpContext);
            }

            return Ok(status);
        }
    }
}
